package com.power.ding.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.core.common.file.FileController;
import com.plf.core.common.service.BaseServiceImpl;
import com.power.ding.exception.DingException;
import com.power.ding.model.enumeration.St_pStatus;
import com.power.ding.service.SystemService;
import com.power.sifa.approve.api.IAprv_process_materialsFeign;
import com.power.sifa.approve.model.enumeration.Tp_procmaterial;
import com.power.sifa.approve.model.enumeration.Tp_proctype;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import com.power.ding.model.Di_todo;
import com.power.ding.dao.Di_todoDao;
import com.power.ding.service.Di_todoService;
import com.power.ding.model.pageInfo.Di_todoPageInfo;

import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

/**
 *  钉钉待办发送业务层实现
 */
@Service
public class Di_todoServiceImpl extends BaseServiceImpl implements Di_todoService {

    @Autowired
    private Di_todoDao dao;

    @Resource
    private Di_todoDao di_todoDao;

    @Resource
    private FileController fileController;

    @Resource
    @Lazy
    private SystemService systemService;

    @Resource
    private IAprv_process_materialsFeign iAprv_process_materialsFeign;

    @Override
    public Di_todo getById(Serializable id) {
        return dao.findById(id).orElse(null);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdate(Di_todo di_todo) {
    	// save 如果数据库不存在这条数据，就会执行保存（即将这条数据插入到数据库）；如果数据库存在这条数据，就会根据主键去更新这条数据
        if (di_todo.getPrimaryKey() != null) {
        	 Di_todo di_todofDb = dao.findById(di_todo.getPrimaryKey()).orElse(null);
             if(di_todofDb != null) {
                BeanUtils.copyProperties(di_todo, di_todofDb);
                dao.save(di_todofDb);
                return;
             }
        }
        dao.save(di_todo);
    }

    @Override
    public void removeById(Serializable id) {
        dao.deleteById(id);
    }

    @Override
    public Page<Di_todo> findAll(Di_todoPageInfo pageInfo) {
        //排序等定义
        Sort sort;
        if("asc".equals(pageInfo.getOrder())) {
            sort = Sort.by(Sort.Direction.ASC, pageInfo.getSort());
        }else {
            sort = Sort.by(Sort.Direction.DESC, pageInfo.getSort());
        }
        //分页的定义
        Pageable pageable = PageRequest.of(pageInfo.getPageNumber()<=1 ? 0 : pageInfo.getPageNumber()-1, pageInfo.getPageSize(), sort);
        //查询条件
        Specification spec = this.createSpecification(pageInfo);
        return dao.findAll(spec, pageable);
    }
    
    @Transactional(rollbackFor = Exception.class)
    public void removeByIds(List<Integer> ids) {
        dao.removeByIds(ids);
    }
    
    @Override
	public List<Di_todo> findAll() {
		return dao.findAll();
	}
	
	@Override
	public void saveAll(List<Di_todo> list) {
		dao.saveAll(list);
	}
    @Override
    public PageDataResponse getTodoListByUserid(Di_todoPageInfo pageInfo) throws DingException {
        List<Map<String, Object>> list = di_todoDao.getTodoListByUserid(pageInfo);
        PageDataResponse page = new PageDataResponse();
        if (!CollectionUtils.isEmpty(list)) {
            Long total = (long) pageInfo.getAllcount();
            int size = pageInfo.getPageSize() * pageInfo.getPageNumber();
            if (total.intValue() - size > 0) {
                Integer num = pageInfo.getPageNumber() + 1;
                page.setNextPage(num);
            }
            page.setSize(pageInfo.getPageSize());
            page.setCurrent(pageInfo.getPageNumber());
            page.setTotal(total);
            page.setRecords(list);
            return page;
        } else {
            page.setSize(0);
            page.setCurrent(1);
            page.setTotal(0L);
            return page;
        }
    }

    @Override
    public Map<String, Object> getAttachByApplyid(String applyid, Integer mattype) {
        Map<String, Object> attach = di_todoDao.getAttachByApplyid(applyid, mattype);
        if (!attach.entrySet().isEmpty()) {
            Map<String, Object> result = (Map<String, Object>) fileController.get((String) attach.get("attachid")).getData();
            attach.put("fileUrl", result.get("url"));
            attach.put("fileName", result.get("name"));
        }
        return attach;
    }

    @Override
    public List<Map<String, Object>> getFileListByApplyId(String applyid, Integer mattype) {
            List<Map<String, Object>> filesList = di_todoDao.getFileListByApplyId(applyid, mattype);
        return filesList;
    }


    @Override
    public JSONObject finishRespond(String id, List<MultipartFile> files) throws Exception {
        Di_todo todo = this.getById(id);
        if (todo == null) {
            throw new Exception("待办记录不存在 id=" + id);
        }

        String url = "http://10.19.196.66:9900/sfding-web/pages/respond/respondRedirect?id=" + todo.getId() + "&type=reply";
        todo.setUrl(url);

        JSONObject apiResult = systemService.finishTodo(id);
        if (apiResult.getString("type").equals("success")) {
            todo.setPStatus(St_pStatus.PROCESSED);
            todo.setPTime(Calendar.getInstance().getTime());
            this.saveOrUpdate(todo);
            iAprv_process_materialsFeign.saveMaterialMulti(todo.getApplyid(), Tp_procmaterial.HEAR_REPLYLETTER, Tp_proctype.HEAR_REPLY, todo.getReceiveUserId(),
                    todo.getReceiveUserName(), files);
        } else {
            String error = apiResult.getString("message");
            JSONObject data = apiResult.getJSONObject("data");
            if (data != null && data.getString("errorMessage") != null) {
                error = data.getString("errorMessage");
            }
            todo.setSendError(error);
            this.saveOrUpdate(todo);
            throw new Exception(error);
        }

        return apiResult;
    }
}
